package selenium;

import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.InputFormatException;

public class 多线程测试 {
	// ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆唯一更改◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆
	private static String filepath = "H:\\趣多拍\\视频采集\\视频";// F:\\未解析
	private String zhangHaoLeixing = "影视号";// 文件夹和账户名都是这个
	private String zhangHaoLeixingBeiFen = "影视号备份";// 全账号备份保底
	private static int adsl = 17;// 选择第几条宽带? 12就是下面第12条线路。
	private static int faSongAmount = 1;// 发送数量

	private String leimuLeiXing = "影视";// 相对于代码的目录文件夹名称，如果是最外面一层，请留空
	private static int isXiGua = 1;// 视频来源： 是西瓜视频？影视类目不管是不是西瓜，都选1.
	private static int ipsRepetition = 100;// 移动宽带100个IP数内禁止重复
	private static int liantongAdsl = 60;// 非移动宽带60个IP数内禁止重复
	private int wuGanRao = 0;// 0为有干扰,浏览器可见。1为无干扰，浏览器不可见。
	private int patternAPP = 1;// 1为APP模式。
	private int jianrongWin7 = 0;// 1为兼容win7模式。
	private int displayAmount = 1;
	private String tagsMulu = "影视标签";// 标签名称
	private String[] leimu = { "电视剧-电视剧片段" };// 类目
	private String titleBetter = "影视标题优化";// 标题优化文件词汇库
	private static String javaPath = "D";// java文件夹在哪里？
	private static String peiZhiPath = "C";// 日志，账号，PPOE拨号
	// ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆唯一更改◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆

	private String[] adslZhangHaos = { "hudqa05728327-728327-宽带连接", // ---宽带帐号1---小微宽带100M下载100M上传。--天恩A
			"hudqb05728327-728327-宽带连接", // ---宽带帐号2---小微宽带200M下载50M上传。
			"hudqc05728327-728327-宽带连接", // ---宽带帐号3---小微宽带100M下载100M上传。--天恩C
			"hudqd05728327-728327-宽带连接", // ---宽带帐号4---小微宽带100M下载100M上传。--天恩D
			"hudqe05728327-728327-宽带连接", // ---宽带帐号5---小微宽带100M下载100M上传。--天恩E
			"hudqf05728327-728327-宽带连接", // ---宽带帐号6---小微宽带100M下载100M上传。
			"hudqg05728327-728327-宽带连接", // ---宽带帐号7---小微宽带100M下载100M上传。
			"hudqa57231886-231886-宽带连接", // ---宽带帐号8---家庭宽带100M下载30M上传。---天恩妈
			"hudqa06822005-822005-宽带连接", // ---宽带帐号9---家庭宽带100M下载30M上传。---天恩爸
			"hudqa77427708-427708-宽带连接", // ---宽带帐号10--家庭宽带200M下载60M上传。
			"057241431528-448887-宽带连接", // ----宽带帐号11--电信宽带100M下载4M上传。----天恩可双拨
			"18105728327-823233-宽带连接", // -----宽带帐号12--电信宽带200M下载10M上传。
			"h18105728327-280013-宽带连接", // ----宽带帐号13--联通宽带50M下载20M上传。----天恩可双拨0
			"h118105728327-280013-宽带连接", // ---宽带帐号14--联通宽带50M下载20M上传。----天恩可双拨1
			"h218105728327-280013-宽带连接", // ---宽带帐号15--联通宽带50M下载20M上传。----天恩可双拨2
			"h318105728327-280013-宽带连接", // ---宽带帐号16--联通宽带50M下载20M上传。----车库联通第四条
			"15272878545-139484-宽带连接", // -----宽带帐号17--随州移动宽带50M下载20M上传。
	};

	public static void main(String[] args) {
		多线程测试 muDemo = new 多线程测试();
		for (int i = 0; i < 999999999; i++) {
			try {
				doClean(filepath);
				muDemo.do163(filepath, isXiGua);
			} catch (Exception e) {
				i--;
				continue;
			}
		}
	}

	private String adslZhangHao = adslZhangHaos[adsl - 1].trim();
	// **************检测出现问题的帐号和出现问题的视频****************
	private static String jishuZhangHuString = "";
	private static int jishuZhangHuCount = 0;
	private static String jishuShiPingString = "";
	private static int jishuShiPingCount = 0;
	private static int jinDuTiaoCount = 0;
	// **************检测出现问题的帐号和出现问题的视频****************
	private static List<String> ips = new ArrayList<String>();// 存取IP,不准和前面的70个IP重复，内存版不写入文件

	public void do163(String filepath, Integer isXiGua) throws Exception {
		int zhenChangAmount = 6;// 网易正常数量目前是6
		String minGanCis = "敏感词";
		String peizhiFile = peiZhiPath + ":\\网易号配置文件";
		File adslZhangHaofile = new File(peizhiFile + "/adsl.txt");
		String adslZhangHaoReal = new String(adslZhangHao.toString());
		if (adslZhangHaofile.exists()) {
			List<String> adslZhangHaoList = readFile(peizhiFile + "\\adsl.txt", null);
			if (adslZhangHaoList.size() > 0) {
				String str = adslZhangHaoList.get(0).trim();
				adslZhangHaoReal = new String(str).trim();
			}
		}
		connAdsl(adslZhangHaoReal);
		int dengdai;// 等待视频上传时间长度。单位/秒
		if (adslZhangHaoReal.contains("1528")) {
			dengdai = 240;
			displayAmount = 2;
		} else if (adslZhangHaoReal.contains("1656")) {
			dengdai = 100;
			displayAmount = 1;
		} else if (adslZhangHaoReal.contains("hudq")) {
			dengdai = 40;
		} else if (adslZhangHaoReal.contains("0020")) {
			dengdai = 100;
		} else if (adslZhangHaoReal.contains("7287")) {
			dengdai = 100;
		} else {
			dengdai = 70;
		}
		int katushijian = 20;// 视频100%到网易返回图片之间的时间差
		int tanChuangTiaoGuo = 200;// 设置超时时间为0.2S，alert().accept()
		List<String> leimuList = new ArrayList<String>(Arrays.asList(leimu));
		Collections.shuffle(leimuList);
		Pattern patPunc = Pattern.compile("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]$");
		// 第几张图片
		String[] dianjitupian = { "//*[@id='auto']/ul/li[1]", "//*[@id='auto']/ul/li[2]", "//*[@id='auto']/ul/li[3]",
				"//*[@id='auto']/ul/li[4]", "//*[@id='auto']/ul/li[5]", "//*[@id='auto']/ul/li[6]",
				"//*[@id='auto']/ul/li[7]", "//*[@id='auto']/ul/li[8]", "//*[@id='auto']/ul/li[9]",
				"//*[@id='auto']/ul/li[10]", "//*[@id='auto']/ul/li[11]", "//*[@id='auto']/ul/li[12]" };
		int max = 10;
		int min = 3;

		String zhangHaofilepath = peiZhiPath + ":/网易号/帐号/" + zhangHaoLeixing;// 帐号文件夹路径

		SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date currentTime = new Date();
		String dateString = format1.format(currentTime);
		Random random = new Random();
		// **************生成帐号文件类型文件夹****************
		File zhangHaofile = new File(zhangHaofilepath);
		if (!zhangHaofile.exists()) {
			zhangHaofile.mkdirs();
		}
		// **************生成帐号文件类型文件夹****************

		// **************生成帐号故障文件夹****************
		String zhangHaoGuZhang = peiZhiPath + ":/网易号/网易号日志";
		File zhangHaoGuZhangfile = new File(zhangHaoGuZhang);
		if (!zhangHaoGuZhangfile.exists()) {
			zhangHaoGuZhangfile.mkdirs();
		}
		// **************生成帐号故障文件夹****************

		// **************生成随机帐号文件列表//帐号重复生成****************
		File zhangHaoExist = new File(zhangHaofilepath + "/" + dateString + ".txt");
		String peizhiCpan = peiZhiPath + ":/网易号配置文件";
		if (!zhangHaoExist.exists()) {
			File zhangHaoCpan = new File(peizhiCpan + "/account.txt");
			if (!zhangHaoCpan.exists()) {
				List<String> listFile = readFileAll(this.getClass().getResource("/").getPath() + "/" + leimuLeiXing
						+ "/" + zhangHaoLeixing + ".txt");
				Collections.shuffle(listFile);
				writeFile(zhangHaofilepath + "/" + dateString + ".txt", listFile);
			} else {
				List<String> listFile = readFileAll(peizhiCpan + "/account.txt");
				Collections.shuffle(listFile);
				writeFile(zhangHaofilepath + "/" + dateString + ".txt", listFile);
			}
		}
		List<String> chongXinShenChenList = readFileAll(zhangHaofilepath + "/" + dateString + ".txt");
		if (chongXinShenChenList.size() < 1) {
			File zhangHaoCpan = new File(peizhiCpan + "/account.txt");
			if (!zhangHaoCpan.exists()) {
				List<String> listFile = readFileAll(this.getClass().getResource("/").getPath() + "/" + leimuLeiXing
						+ "/" + zhangHaoLeixingBeiFen + ".txt");
				Collections.shuffle(listFile);
				writeFile(zhangHaofilepath + "/" + dateString + ".txt", listFile);
			} else {
				List<String> listFile = readFileAll(peizhiCpan + "/account.txt");
				Collections.shuffle(listFile);
				writeFile(zhangHaofilepath + "/" + dateString + ".txt", listFile);
			}
		}
		// **************生成随机帐号文件列表****************

		// **************标题优化，标签优化，敏感词****************String docFilePath =
		// "./ExportWord.doc";
		List<String> listTitleBetter = readFileAll(
				this.getClass().getResource("/").getPath() + "/" + leimuLeiXing + "/" + titleBetter + ".txt");
		List<String> listTagsFile = readFileAll(
				this.getClass().getResource("/").getPath() + "/" + leimuLeiXing + "/" + tagsMulu + ".txt");
		List<String> listMinGanCis = readFileAll(this.getClass().getResource("/").getPath() + "/" + minGanCis + ".txt");
		// **************标题优化，标签优化，敏感词****************

		// **************生成随机视频文件列表列表****************
		File shiPingAExist = new File(filepath + "/顺序.txt");// 读视频文件
		if (!shiPingAExist.exists()) {
			File fileExist = new File(filepath);
			String[] filelist = fileExist.list();
			for (int i = 0; i < filelist.length; i++) {
				String fileName = filelist[i];
				String endWith123 = fileName.split(".mp4")[0];
				if ((!fileName.endsWith(".mp4")) || endWith123.endsWith(")")) {
					continue;
				}
				method2(filepath + "/顺序" + ".txt", filepath + "/" + fileName);
			}
			List<String> listFile = readFileAll(filepath + "/" + "顺序" + ".txt");
			Collections.shuffle(listFile);
			writeFile(filepath + "/乱序.txt", listFile);
		}
		// **************生成随机视频文件列表列表****************

		// **************检测帐号是不是已经全部发送完和视频是不是已经没有了****************
		List<String> listZhangHaoCount = readFileAll(zhangHaofilepath + "/" + dateString + ".txt");
		List<String> listShiPingCount = readFileAll(filepath + "/" + "乱序" + ".txt");
		System.out.println("◆◆◆◆◆◆◆◆◆◆◆");
		System.out.println("还存在【" + listZhangHaoCount.size() + "个帐号】");
		System.out.println("还存在【" + listShiPingCount.size() + "个视频】");
		System.out.println("◆◆◆◆◆◆◆◆◆◆◆");
		if (listZhangHaoCount.size() < 1 || listShiPingCount.size() < 1) {
			Thread.sleep(5 * 1000 * 60);// 5分钟
		}
		// **************检测帐号是不是已经全部发送完和视频是不是已经没有了****************

		int width = Toolkit.getDefaultToolkit().getScreenSize().width;
		int zuobiaoWidth = 500;// 宽度坐标
		int zuobiaoHeight = 300;// 高度坐标
		int chromeWidth = 300;// 浏览器高度
		int chromeHeight = 300;// 浏览器高度
		if (wuGanRao == 1) {
			zuobiaoWidth = 200;
			zuobiaoHeight = 1100;
		} else {
			if (width == 1280) {
				zuobiaoWidth = 500;
				zuobiaoHeight = 150;
				chromeWidth = 780;
				chromeHeight = 830;
			} else if (width == 1366) {
				zuobiaoWidth = 500;
				zuobiaoHeight = 150;
				chromeWidth = 866;
				chromeHeight = 518;
			} else if (width == 1440) {
				zuobiaoWidth = 500;
				zuobiaoHeight = 150;
				chromeWidth = 940;
				chromeHeight = 650;
			} else if (width == 1600) {
				zuobiaoWidth = 500;
				zuobiaoHeight = 150;
				chromeWidth = 1100;
				chromeHeight = 650;
			} else if (width == 1920 && displayAmount == 2) {
				zuobiaoWidth = 2000;
				zuobiaoHeight = 150;
				chromeWidth = 1000;
				chromeHeight = 400;
			} else if (width == 1920 && displayAmount == 1) {
				zuobiaoWidth = 500;
				zuobiaoHeight = 150;
				chromeWidth = 1420;
				chromeHeight = 830;
			} else {
				zuobiaoWidth = 500;
				zuobiaoHeight = 150;
				chromeWidth = 866;
				chromeHeight = 668;
			}
		}
		Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");
		Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");
		Thread.sleep(300);
		String chromedriverExist = javaPath + ":/java/chromedriver.exe";
		File chromedriverFileExist = new File(chromedriverExist);// 读driver
		if (!chromedriverFileExist.exists()) {
			chromedriverExist = javaPath + ":/java/chromedriver_win32/chromedriver.exe";
		}
		System.getProperties().setProperty("webdriver.chrome.driver", chromedriverExist);
		// 指定设备的分辨率及像素比
		Map<String, Object> deviceMetrics = new HashMap<String, Object>();
		/*
		 * deviceMetrics.put("width", 360); deviceMetrics.put("height", 640);
		 */
		deviceMetrics.put("pixelRatio", 1);

		Map<String, Object> mobileEmulation = new HashMap<String, Object>();
		mobileEmulation.put("deviceMetrics", deviceMetrics);
		// 指定设备的userAgent(此处是一个微信内置浏览器)
		mobileEmulation.put("userAgent",
				"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 MicroMessenger/6.5.12 NetType/WIFI Language/zh_CN");
		List<String> args = new ArrayList<String>();
		args.add("window-size=1,1"); // 设置浏览器窗口大小
		args.add("disable-infobars");
		if (patternAPP == 1) {
			args.add("app=https://www.baidu.com/");
		}
		Map<String, Object> chromeOptions = new HashMap<String, Object>();
		if (jianrongWin7 == 1) {
			chromeOptions.put("mobileEmulation", mobileEmulation);
		}
		chromeOptions.put("args", args);
		DesiredCapabilities capabilities = DesiredCapabilities.chrome();
		capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
		final WebDriver driver = new ChromeDriver(capabilities);
		Point targetPosition = new Point(zuobiaoWidth, zuobiaoHeight);
		driver.manage().window().setPosition(targetPosition);
		if (wuGanRao == 0) {
			Dimension dimension = new Dimension(chromeWidth, chromeHeight);
			driver.manage().window().setSize(dimension); // 将浏览器的大小自定义为600*400
		}
		if (width == 1920 && displayAmount == 2 && wuGanRao == 0) {
			driver.manage().window().maximize();
		}
		System.gc();
		driver.get("http://mp.163.com/wemedia/baseinfo/isexist/1");
		JavascriptExecutor js = (JavascriptExecutor) driver;
		try {
			for (int z = 0; z < 99999; z++) {
				driver.manage().deleteAllCookies();
				System.gc();
				SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy hh:mm:ss a", Locale.US);

				String name = "NTES_SESS";
				// 读取帐号文件

				List<String> zhanghus = readFileAll(zhangHaofilepath + "/" + dateString + ".txt");
				if (zhanghus.size() < 1) {
					System.out.println("没账户了");
					Date currentNewTime = new Date();
					String dateNewString = format1.format(currentNewTime);
					File zhangHaoNewExist = new File(zhangHaofilepath + "/" + dateNewString + ".txt");// 读视频文件
					if (!zhangHaoNewExist.exists()) {
						throw new RuntimeException();
					}
				}
				String zhangHu = zhanghus.get(0).trim();

				// **************查账户重复登录不进去的情况，防止卡在一个账户上进行不下去****************
				if (!jishuZhangHuString.equals(zhangHu)) {
					jishuZhangHuString = zhangHu;
					jishuZhangHuCount = 0;
				} else {
					jishuZhangHuString = zhangHu;
					jishuZhangHuCount++;
					if (jishuZhangHuCount >= 6) {// 6次都发不出去，说明这个账户有问题
						// 删除帐号第一行
						List<String> listZhangHao = readFile(zhangHaofilepath + "/" + dateString + ".txt", zhangHu);
						writeFile(zhangHaofilepath + "/" + dateString + ".txt", listZhangHao);
						System.out.println("还有(" + listZhangHao.size() + ")个【帐号】没有传输完");
						String[] zhangHuSubStrings = zhangHu.split("\\/", -1);
						String zhangHuSubString = zhangHuSubStrings[0] + "----" + zhangHuSubStrings[1] + "----"
								+ zhangHuSubStrings[2] + "----" + zhangHuSubStrings[3];
						writeContent(zhangHaoGuZhang + "/" + "账户6次循环不过去" + dateString + ".txt",
								format0.format(new Date()) + "----" + zhangHuSubString);
						continue;
					}
				}
				// **************查账户重复登录不进去的情况，防止卡在一个账户上进行不下去****************

				String[] s1 = zhangHu.split("\\/", -1);
				String value = s1[4];
				System.out.println(s1[0] + "----" + s1[1] + "----【" + s1[2] + "】----开始执行任务");
				String domain = ".mp.163.com";
				String path = "/";
				Date expiry = sdf.parse("1/30/2028 10:31:37 AM");
				Cookie cookie = new Cookie(name, value, domain, path, expiry);
				driver.manage().addCookie(cookie);
				String idString = s1[3];
				String videoUrl = "http://mp.163.com/video/postpage/" + idString;
				for (int y = 0; y < 999; y++) {
					System.gc();
					Callable<Integer> callableADSL = () -> {
						driver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);
						driver.get(videoUrl);
						return 1;
					};
					for (int i = 0; i < 9999; i++) {
						// 代码2, 代码2 运行的最长时间为 timeout
						int timeout = 3000;
						Integer timeoutValue = -1;
						TimeoutCallable<Integer> timeoutCallable = new TimeoutCallable<>(callableADSL, timeout,
								timeoutValue);
						ExecutorService executor = Executors.newSingleThreadExecutor();
						Future<Integer> future = executor.submit(timeoutCallable);

						Integer result = future.get();
						// end 代码2
						// 代码3
						if (timeoutValue.equals(result)) {
							System.out.println(executor.shutdownNow().toString());
							executor.shutdown();
							System.out.println("请求发生故障,从头再来");
							driver.get("https://www.baidu.com/");
							continue;
						} else {
							System.out.println("【上传视频页面】任务结果：" + result);
							break;
						}
						// end 代码3
					}
					WebElement maxCount = driver.findElement(By.xpath("//*[@id='mainContent']/div[1]/span[1]/span"));
					String iMaxCount = maxCount.getText();
					System.out.println(iMaxCount);
					String todayMax = iMaxCount.split("\\/")[1];
					String s = iMaxCount.split("\\/")[0];
					String todayAready = s.split("：")[1];
					y = Integer.parseInt(todayAready);
					int yMax = Integer.parseInt(todayMax);
					System.out.println("正在处理第【" + (y + 1) + "】个视频");
					if (y >= yMax) {
						System.out.println("已经发送数量为----" + y + "----此帐号本次任务已达标，结束任务！");
						break;
					}
					if (faSongAmount == zhenChangAmount) {
						System.out.println("正常发送，发到最大值----【" + yMax + "个】");
					} else {
						yMax = faSongAmount;
						if (y >= yMax) {
							System.out.println("限制发送，发到限制值----【" + y + "】----任务已达标，结束！");
							break;
						}
					}
					List<String> listZhangHaoCount1 = readFileAll(zhangHaofilepath + "/" + dateString + ".txt");
					System.out.println("还有(" + listZhangHaoCount1.size() + ")个【帐号】没有传输完");

					// **************删除左边右边和上边多余信息****************
					WebElement page_bd_minor = driver.findElement(By.className("page__bd__minor"));
					js.executeScript("arguments[0].remove()", page_bd_minor);
					WebElement rightTool = driver.findElement(By.className("right-tool"));
					js.executeScript("arguments[0].remove()", rightTool);
					WebElement page_hd_header = driver.findElement(By.className("page__hd"));
					js.executeScript("arguments[0].remove()", page_hd_header);
					// **************删除左边右边和上边多余信息****************

					// 读取视频地址
					List<String> shiPings = readFileAll(filepath + "/" + "乱序" + ".txt");
					if (shiPings.size() < 1) {
						System.err.println("没视频了");
						throw new RuntimeException();
					}
					String shiPing = shiPings.get(0).trim();
					String shouzimu = filepath.substring(0, 1);
					String zhuanhuan = shiPing.substring(1);
					String realShiPing = new String(shouzimu + zhuanhuan);// 防止换磁盘的时候盘符字母改变
					System.out.println("读入视频文件成功：" + realShiPing);
					String yanzhengShiPing = shiPing.split(".mp4")[0].trim();

					// ****************重复过滤视频，防止重复*****************
					File mp4Exist = new File(realShiPing);
					if (!mp4Exist.exists()) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("视频不存在删除成功");
						continue;
					}
					String str123 = new String(yanzhengShiPing);
					str123 = yanzhengShiPing.substring(yanzhengShiPing.length() - 1, yanzhengShiPing.length());
					if (isNum(str123)) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("末位为数字的视频删除成功");
						continue;
					}
					if (endingChar(str123)) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("末位为字母的视频删除成功");
						continue;
					}
					if (yanzhengShiPing.endsWith(")")) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("重复下载的视频删除成功");
						continue;
					}
					String[] shiPinglenths = yanzhengShiPing.split("/");
					String shiPinglenth = shiPinglenths[shiPinglenths.length - 1];
					if (shiPinglenth.length() < 10 || shiPinglenth.length() > 50) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("文件名小于11大于50删除成功");
						continue;
					}
					if (!shiPing.endsWith(".mp4") || yanzhengShiPing.endsWith("）")) {// 视频不存在也删除
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("非MP4文件删除成功");
						continue;
					}
					if (yanzhengShiPing.endsWith("）")) {// 恶意添加中文"）"符号的删除
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						y--;
						System.err.println("恶意添加中文）符号的删除成功");
						continue;
					}
					// ****************重复过滤视频，防止重复*****************

					// **************查视频重复发不出去的情况，防止卡在一个视频上进行不下去****************
					if (!jishuShiPingString.equals(shiPing)) {
						jishuShiPingString = shiPing;
						jishuShiPingCount = 0;
					} else {
						jishuShiPingString = shiPing;
						jishuShiPingCount++;
						if (jishuShiPingCount >= 6) {// 6次都发不出去，说明这个视频有严重问题
							// 删除第一行
							List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
							writeFile(filepath + "/" + "乱序" + ".txt", listFile);
							if (mp4Exist.exists()) {
								System.gc();
								mp4Exist.delete();
							}
							y--;
							writeContent(zhangHaoGuZhang + "/" + "视频6次循环不过去" + dateString + ".txt",
									format0.format(new Date()) + "----" + shiPing);
							continue;
						}
					}
					// **************查视频重复发不出去的情况，防止卡在一个视频上进行不下去****************

					// **************敏感词过滤，比如：毛主席，周恩来，中共****************
					int minGanState = 0;
					for (String string : listMinGanCis) {// 敏感词过滤
						if (shiPing.indexOf(string.trim()) > -1) {
							// 删除第一行
							List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
							writeFile(filepath + "/" + "乱序" + ".txt", listFile);
							if (mp4Exist.exists()) {
								System.gc();
								mp4Exist.delete();
							}
							y--;
							writeContent(zhangHaoGuZhang + "/" + "含有敏感词视频" + ".txt",
									format0.format(new Date()) + "----" + shiPing);
							minGanState = 1;
							break;
						}
					}
					if (minGanState == 1) {
						continue;
					}
					// **************敏感词过滤，比如：毛主席，周恩来，中共****************

					driver.findElement(By.id("video-up-input")).sendKeys(realShiPing);
					driver.findElement(By.xpath("//form[@id='videoPost']/div[2]/div[6]/div/ul/li[1]/a/label")).click();// 视频封面自动
					// 标题和复制标题开始,,,,最后一段才是真正的精华！
					String valueFileTitle99 = driver.findElement(By.id("fileTitle")).getAttribute("value");
					String valueFileTitle = valueFileTitle99.replace("…", "。");
					// ----------解决超过30字符和小于11字符---开始
					String valueFileTitleNew = new String(valueFileTitle);
					String numberLength = driver.findElement(By.className("j-checkTitle")).getText();
					int intNumberMax = Integer.parseInt(numberLength);
					if (intNumberMax < 15) {
						String titleMore = listTitleBetter.get(random.nextInt(listTitleBetter.size() - 1)).toString();
						Matcher matcher = patPunc.matcher(valueFileTitleNew);
						if (matcher.find()) {
							valueFileTitleNew = new String(valueFileTitleNew + titleMore.replace("\r\n", ""));
						} else {
							valueFileTitleNew = new String(valueFileTitleNew + "，" + titleMore.replace("\r\n", ""));
						}
						driver.findElement(By.id("fileTitle")).clear();
						driver.findElement(By.id("fileTitle")).sendKeys(valueFileTitleNew);
					} else {
						driver.findElement(By.id("fileTitle")).clear();
						driver.findElement(By.id("fileTitle")).sendKeys(valueFileTitleNew);
					}
					// ----------解决超过30字符和小于11字符---结束

					String description = new String(valueFileTitle);
					driver.findElement(By.id("description")).sendKeys(description);// descriptionBetter

					// 贴标签开始
					List<String> listTags = listTagsFile;
					Collections.shuffle(listTags);

					// ------------------贴标签开始------------------//
					Actions action = new Actions(driver);
					for (int i = 0; i < 5; i++) {
						driver.findElement(By.id("form-tags-input")).sendKeys(listTags.get(i));
						action.sendKeys(Keys.SPACE).perform();
					}
					// ------------------贴标签结束------------------//

					String leimufuzhi = leimuList.get(random.nextInt(leimuList.size()));

					String leimuAll = new String(leimufuzhi);
					String[] leimu12 = leimuAll.split("-");
					String leimu1 = leimu12[0];
					String leimu2 = leimu12[1];

					WebElement lisElement = driver
							.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/div"));
					List<WebElement> lis = lisElement.findElements(By.tagName("li"));
					System.out.println("LI标签长度为------" + lis.size());
					if (lis.size() < 49) {
						driver.get("https://www.baidu.com/");
						Thread.sleep(100);
						driver.switchTo().alert().accept();
						Thread.sleep(tanChuangTiaoGuo);
						y--;
						continue;
					}
					driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/button")).click();
					driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[1]/div/div/input"))
							.sendKeys(leimu1.substring(0, 1));
					Thread.sleep(50);
					driver.findElement(By.linkText(leimu1)).click();
					Thread.sleep(100);

					// 弹起电视剧片段
					driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[4]/div/div[2]/button")).click();
					Thread.sleep(50);
					driver.findElement(By.linkText(leimu2)).click();

					/************* 突破30字符 ****************/
					System.out.println("解除标题【字数限制】");
					// *[@id="videoPost"]/div[2]/div[1]
					WebElement editor = driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[1]"));
					js.executeScript("arguments[0].setAttribute('class','')", editor);
					/************* 突破30字符 ***************/
					Thread.sleep(50);

					/************* 描述中含有违规内容，请修改 ***************/
					WebElement weiguiElement = driver
							.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[2]/div/p[1]/span"));
					if (weiguiElement.getText().contains("违规") || weiguiElement.getText().contains("非法")) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						System.out.println("还有(" + listFile.size() + ")个【视频】没有发送");
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						driver.get("https://www.baidu.com/");
						Thread.sleep(100);
						driver.switchTo().alert().accept();
						Thread.sleep(tanChuangTiaoGuo);
						y--;
						continue;
					}
					/************* 描述中含有违规内容，请修改 ***************/

					/************* 卡在0.00%不动解决方案 ***************/
					WebElement kazhu100 = driver.findElement(By.xpath("//*[@id='videoUp']/div/div[2]/span[2]"));
					if (kazhu100 != null && "0%".equals(kazhu100.getText())) {
						// 删除第一行
						List<String> listFile = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
						System.out.println("这个视频是损坏的，直接删除");
						writeFile(filepath + "/" + "乱序" + ".txt", listFile);
						if (mp4Exist.exists()) {
							System.gc();
							mp4Exist.delete();
						}
						driver.get("https://www.baidu.com/");
						Thread.sleep(100);
						driver.switchTo().alert().accept();
						Thread.sleep(tanChuangTiaoGuo);
						y--;
						continue;
					}
					/************* 卡在0.00%不动解决方案 ***************/

					/************* 提交按钮删除样式 ***************/
					JavascriptExecutor jsbutton = (JavascriptExecutor) driver;
					WebElement editorbutton = driver.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[7]/button"));
					jsbutton.executeScript("arguments[0].removeAttribute('class')", editorbutton);
					/************* 提交按钮删除样式 ***************/

					// **************等待时间90秒****************
					for (int i = 0; i < dengdai; i++) {
						try {
							WebDriverWait wait = new WebDriverWait(driver, 1);
							wait.until(new ExpectedCondition<WebElement>() {
								@Override
								public WebElement apply(WebDriver d) {
									WebElement ddElement = driver.findElement(By.className("percent"));
									String baifenbi = ddElement.getText();
									// jinDuTiaoCount
									if (jinDuTiaoCount < 7) {
										jinDuTiaoCount++;
										System.out.print("-" + baifenbi);
									} else {
										jinDuTiaoCount = 0;
										System.out.println("-" + baifenbi);
									}

									if ("100%".equals(baifenbi) || StringUtils.isEmpty(baifenbi)) {
										return ddElement;
									} else {
										return null;
									}
								}
							});
						} catch (Exception e1) {
							continue;
						}
					}
					// **************等待时间90秒****************

					// *************重复内容检测已经前置
					try {
						(new WebDriverWait(driver, 1)).until(new ExpectedCondition<WebElement>() {
							@Override
							public WebElement apply(WebDriver arg0) {
								System.out.println("/html/body/div[7]/div[2]/div/div[2]/div/span[2]--前置视频重复--检测中");
								WebElement sDriver = driver
										.findElement(By.xpath("/html/body/div[7]/div[2]/div/div[2]/div/span[2]"));
								if (sDriver != null) {
									System.out.println("/html/body/div[7]/div[2]/div/div[2]/div/span[2]--成功检测到");
									return sDriver;
								} else {
									return null;
								}
							}
						});
						WebElement beforTip = driver
								.findElement(By.xpath("/html/body/div[7]/div[2]/div/div[2]/div/span[2]"));
						if (beforTip != null) {
							String beforTipString = beforTip.getText();
							if (beforTipString.contains("重复")) {
								writeContent(zhangHaoGuZhang + "/" + "与平台视频重复" + dateString + ".txt",
										format0.format(new Date()) + "----" + shiPing);
								System.err.println("视频重复，在前置阶段被检测到，现在已删除");
								driver.get("https://www.baidu.com/");
								Thread.sleep(100);
								driver.switchTo().alert().accept();
								Thread.sleep(tanChuangTiaoGuo);
								// 删除视频第一行
								List<String> listShiPing = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
								System.out.println("还有(" + listShiPing.size() + ")个【视频】没有发送");
								writeFile(filepath + "/" + "乱序" + ".txt", listShiPing);
								if (mp4Exist.exists()) {
									System.gc();
									mp4Exist.delete();
								}
								continue;
							}
						}
					} catch (Exception e1) {
						System.err.println("前置检测中，本视频没有检测到重复！");
					}
					// *************重复内容检测已经前置

					// ***从100%到卡住图片之间超过自定义秒数，就退出重来***
					System.out.println("100%到卡图片之间");
					for (int i = 0; i < katushijian; i++) {
						try {
							(new WebDriverWait(driver, 1)).until(new ExpectedCondition<WebElement>() {
								@Override
								public WebElement apply(WebDriver arg0) {
									WebElement kazhu100 = driver.findElement(By.className("radio-img"));
									if (kazhu100 != null) {
										return kazhu100;
									} else {
										return null;
									}
								}
							});
						} catch (Exception e) {
							continue;
						}
					}
					// ***从100%到卡住图片之间超过自定义秒数，就退出重来***

					// **************解决空白图片被选中****************
					WebElement tupianAmount = driver.findElement(By.xpath("//*[@id='auto']/ul"));
					List<WebElement> liAmount = tupianAmount.findElements(By.tagName("li"));
					if (0 < liAmount.size() && liAmount.size() < 12) {
						for (int i = 0; i < 9; i++) {
							WebElement tupianClick = driver
									.findElement(By.xpath(dianjitupian[random.nextInt(liAmount.size() - 1)]));
							WebElement tupianToImg = tupianClick.findElement(By.tagName("input"));
							Thread.sleep(50);
							if (StringUtils.isNotEmpty(tupianToImg.getAttribute("value"))) {
								tupianClick.click();
								break;
							}
						}
					} else {
						for (int i = 0; i < 9; i++) {
							WebElement tupianClick = driver.findElement(By.xpath(dianjitupian[0]));
							if (isXiGua == 1) {
								tupianClick = driver.findElement(By.xpath(dianjitupian[0]));
							} else {
								tupianClick = driver.findElement(
										By.xpath(dianjitupian[random.nextInt((max) % (max - min + 1) + min - 1)]));
							}
							WebElement tupianToImg = tupianClick.findElement(By.tagName("input"));
							Thread.sleep(50);
							if (StringUtils.isNotEmpty(tupianToImg.getAttribute("value"))) {
								try {
									for (int j = 0; j < 3; j++) {
										tupianClick.click();
									}
								} catch (Exception e) {
									System.err.println("图片点击出现了毛病，跳过不管");
								}
								break;
							}
						}
					}
					// **************解决空白图片被选中****************

					System.out.println("视频图片被成功选中");

					/************* 防止IP探测 ****************/
					JavascriptExecutor jsIp = (JavascriptExecutor) driver;
					// *[@id="inContent"]/input[6]
					WebElement editorIp = driver.findElement(By.xpath("//*[@id='inContent']/input[6]"));
					System.out.println("更改前内网IP为：" + editorIp.getAttribute("value").toString());
					String ip = String.valueOf(random.nextInt(125)) + "." + String.valueOf(random.nextInt(254)) + "."
							+ String.valueOf(random.nextInt(254)) + "." + String.valueOf(random.nextInt(254));
					jsIp.executeScript("arguments[0].value=\"" + ip + "\"", editorIp);
					/************* 防止IP探测 ***************/

					/************* 提交按钮弹窗出来 ***************/
					for (int i = 0; i < 9; i++) {
						System.out.println("循环：----" + i);
						WebElement jsElement = driver
								.findElement(By.xpath("//*[@id='videoPost']/div[2]/div[7]/button"));
						for (int j = 0; j < 1; j++) {
							js.executeScript("arguments[0].click();", jsElement);
						}
						System.err.println("提交按钮成功重复点击--JS方式--" + i);
						if (i == 6) {
							try {
								(new WebDriverWait(driver, 3)).until(new ExpectedCondition<WebElement>() {
									@Override
									public WebElement apply(WebDriver arg0) {
										System.out.println("/html/body/div[8]--检测中");
										WebElement sDriver = driver.findElement(By.xpath("/html/body/div[8]"));
										if (sDriver != null) {
											System.out.println("/html/body/div[8]--成功检测到");
											return sDriver;
										} else {
											return null;
										}
									}
								});
								WebElement closeWebDriver = driver.findElement(By.className("yidun_modal__close"));
								for (int j = 0; j < 3; j++) {
									js.executeScript("arguments[0].click();", closeWebDriver);
								}
								WebElement div9 = driver
										.findElement(By.xpath("/html/body/div[8]/div[2]/div/div[2]/div/span[2]"));
								String tipString = div9.getText();
								for (int j = 0; j < 10; j++) {
									if (StringUtils.isEmpty(tipString)) {
										Thread.sleep(50);
										WebElement div8For = driver.findElement(
												By.xpath("/html/body/div[8]/div[2]/div/div[2]/div/span[2]"));
										tipString = div8For.getText();
									} else {
										break;
									}
								}
								System.err.println("✔✔" + tipString + "✔✔✔✔✔✔✔✔✔✔✔✔✔✔");
								if (tipString.contains("重复")) {
									writeContent(zhangHaoGuZhang + "/" + "与平台视频重复" + dateString + ".txt",
											format0.format(new Date()) + "----" + shiPing);
									driver.get("https://www.baidu.com/");
									Thread.sleep(100);
									driver.switchTo().alert().accept();
									Thread.sleep(tanChuangTiaoGuo);
									// 删除视频第一行
									List<String> listShiPing = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
									System.out.println("还有(" + listShiPing.size() + ")个【视频】没有发送");
									writeFile(filepath + "/" + "乱序" + ".txt", listShiPing);
									if (mp4Exist.exists()) {
										System.gc();
										mp4Exist.delete();
										System.err.println("视频重复--视频删除成功----" + shiPing);
									}
									break;
								} else if (tipString.contains("发布成功")) {
									writeContent(zhangHaoGuZhang + "/" + "发布成功" + dateString + ".txt",
											format0.format(new Date()) + "----" + shiPing);
									driver.get("https://www.baidu.com/");
									Thread.sleep(100);
									driver.switchTo().alert().accept();
									Thread.sleep(tanChuangTiaoGuo);
									// 删除视频第一行
									List<String> listShiPing = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
									System.out.println("还有(" + listShiPing.size() + ")个【视频】没有发送");
									writeFile(filepath + "/" + "乱序" + ".txt", listShiPing);
									if (mp4Exist.exists()) {
										System.gc();
										mp4Exist.delete();
										System.err.println("发布成功--视频删除成功----" + shiPing);
									}
									break;
								} else if (tipString.contains("频繁")) {
									writeContent(zhangHaoGuZhang + "/" + "发文过于频繁" + dateString + ".txt",
											format0.format(new Date()) + "----" + shiPing);
									driver.get("https://www.baidu.com/");
									Thread.sleep(100);
									driver.switchTo().alert().accept();
									Thread.sleep(tanChuangTiaoGuo);
									changeIP(adslZhangHaoReal);// 更换IP
									break;
								} else {
									driver.get("https://www.baidu.com/");
									Thread.sleep(100);
									driver.switchTo().alert().accept();
									Thread.sleep(tanChuangTiaoGuo);
									break;
								}
							} catch (Exception e) {
								System.out.println("i=6 ----提交按钮提交后没有反应----重新尝试提交");
								WebElement closeWebDriver = driver.findElement(By.className("yidun_modal__close"));
								for (int j = 0; j < 3; j++) {
									js.executeScript("arguments[0].click();", closeWebDriver);
								}
								System.err.println("成功关闭了验证码的图片----" + i);
								i = 0;
								continue;
							}
						} else if (i == 1) {
							try {
								(new WebDriverWait(driver, 3)).until(new ExpectedCondition<WebElement>() {
									@Override
									public WebElement apply(WebDriver arg0) {
										System.out.println("/html/body/div[7]--检测中");
										WebElement sDriver = driver.findElement(By.xpath("/html/body/div[7]"));
										if (sDriver != null) {
											System.out.println("/html/body/div[7]--成功检测到");
											return sDriver;
										} else {
											return null;
										}
									}
								});
							} catch (Exception e) {
								System.out.println("i=1 ----提交按钮提交后没有反应----重新尝试提交");
								i = 0;
								continue;
							}
						} else {
							try {
								(new WebDriverWait(driver, 7)).until(new ExpectedCondition<WebElement>() {
									@Override
									public WebElement apply(WebDriver arg0) {
										System.out.println("/html/body/div[7]--检测中");
										WebElement sDriver = driver.findElement(By.xpath("/html/body/div[7]"));
										if (sDriver != null) {
											System.out.println("/html/body/div[7]--成功检测到");
											return sDriver;
										} else {
											return null;
										}
									}
								});
							} catch (Exception e) {
								System.out.println("i=-1 ----提交按钮提交后没有反应----重新尝试提交");
								i = -1;
								continue;
							}
						}
						WebElement yidun_popupDriver = driver.findElement(By.xpath("/html/body/div[7]"));
						String style = yidun_popupDriver.getAttribute("style");
						System.out.println(style);
						if ("display: block;".equals(style)) {
							// yidun_modal__close
							WebElement yidunloseElement = driver.findElement(By.className("yidun_modal__close"));
							for (int j = 0; j < 3; j++) {
								js.executeScript("arguments[0].click();", yidunloseElement);
							}
							i = 5;
							changeIP(adslZhangHaoReal);// 更换IP
							continue;
						} else if (!"display: block;".equals(style) && i == 1) {
							for (int j = 0; j < 2; j++) {
								try {
									(new WebDriverWait(driver, 3)).until(new ExpectedCondition<WebElement>() {
										@Override
										public WebElement apply(WebDriver arg0) {
											System.out.println("display: block;--检测中");
											WebElement yidun_popupDriver = driver
													.findElement(By.xpath("/html/body/div[7]"));
											String style = yidun_popupDriver.getAttribute("style");
											if ("display: block;".equals(style)) {
												System.out.println("display: block;--成功检测到");
												return yidun_popupDriver;
											} else {
												return null;
											}
										}
									});
								} catch (Exception e) {
									System.out.println("display: block; ----(6)秒内检测不到就关闭窗口重新上传");
									continue;
								}
							}
							System.out.println("-----准备点击关闭按钮----");
							WebElement yidun_modal_closeDriver = driver.findElement(By.xpath("/html/body/div[7]"));
							String closetyle = yidun_modal_closeDriver.getAttribute("style");
							System.out.println(closetyle);
							if ("display: block;".equals(closetyle)) {
								WebElement yidunloseElement = driver.findElement(By.className("yidun_modal__close"));
								for (int j = 0; j < 3; j++) {
									js.executeScript("arguments[0].click();", yidunloseElement);
								}
							}
							i = 5;
							String[] zhangHuSubStrings = zhangHu.split("\\/", -1);
							String zhangHuSubString = zhangHuSubStrings[0] + "/" + zhangHuSubStrings[1] + "/"
									+ zhangHuSubStrings[2] + "/" + zhangHuSubStrings[3];
							String guZhangTime = format0.format(new Date());
							String guZhangContent = guZhangTime + "----" + zhangHuSubString;
							writeContent(zhangHaoGuZhang + "/" + "平台响应慢产生的提交故障" + dateString + ".txt",
									format0.format(new Date()) + "----" + guZhangContent);
							driver.get("https://www.baidu.com/");
							Thread.sleep(100);
							driver.switchTo().alert().accept();
							Thread.sleep(tanChuangTiaoGuo);
							break;
						} else if (!"display: block;".equals(style) && i == 0) {
							WebElement div8 = driver
									.findElement(By.xpath("/html/body/div[7]/div[2]/div/div[2]/div/span[2]"));
							String tipString = div8.getText();
							for (int j = 0; j < 10; j++) {
								if (StringUtils.isEmpty(tipString)) {
									Thread.sleep(50);
									WebElement div8For = driver
											.findElement(By.xpath("/html/body/div[7]/div[2]/div/div[2]/div/span[2]"));
									tipString = div8For.getText();
								} else {
									break;
								}
							}
							System.err.println("✔" + tipString + "✔✔✔✔✔✔✔✔✔✔✔✔✔✔");
							if (tipString.contains("重复")) {
								writeContent(zhangHaoGuZhang + "/" + "与平台视频重复" + dateString + ".txt",
										format0.format(new Date()) + "----" + shiPing);
								driver.get("https://www.baidu.com/");
								Thread.sleep(100);
								driver.switchTo().alert().accept();
								Thread.sleep(tanChuangTiaoGuo);
								// 删除视频第一行
								List<String> listShiPing = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
								System.out.println("还有(" + listShiPing.size() + ")个【视频】没有发送");
								writeFile(filepath + "/" + "乱序" + ".txt", listShiPing);
								if (mp4Exist.exists()) {
									System.gc();
									mp4Exist.delete();
									System.err.println("重复--视频删除成功----" + shiPing);
								}
								break;
							} else if (tipString.contains("发布成功")) {
								writeContent(zhangHaoGuZhang + "/" + "发布成功" + dateString + ".txt",
										format0.format(new Date()) + "----" + shiPing);
								driver.get("https://www.baidu.com/");
								Thread.sleep(100);
								driver.switchTo().alert().accept();
								Thread.sleep(tanChuangTiaoGuo);
								// 删除视频第一行
								List<String> listShiPing = readFile(filepath + "/" + "乱序" + ".txt", shiPing);
								System.out.println("还有(" + listShiPing.size() + ")个【视频】没有发送");
								writeFile(filepath + "/" + "乱序" + ".txt", listShiPing);
								if (mp4Exist.exists()) {
									System.gc();
									mp4Exist.delete();
									System.err.println("成功--视频删除成功----" + shiPing);
								}
								break;
							} else if (tipString.contains("频繁")) {
								writeContent(zhangHaoGuZhang + "/" + "发文过于频繁" + dateString + ".txt",
										format0.format(new Date()) + "----" + shiPing);
								driver.get("https://www.baidu.com/");
								Thread.sleep(100);
								driver.switchTo().alert().accept();
								Thread.sleep(tanChuangTiaoGuo);
								changeIP(adslZhangHaoReal);// 更换IP
								break;
							} else {
								driver.get("https://www.baidu.com/");
								Thread.sleep(100);
								driver.switchTo().alert().accept();
								Thread.sleep(tanChuangTiaoGuo);
								break;
							}
						}
					}
					/************* 提交按钮弹窗出来 ***************/
				}
				// 删除帐号第一行
				List<String> listZhangHao = readFile(zhangHaofilepath + "/" + dateString + ".txt", zhangHu);
				writeFile(zhangHaofilepath + "/" + dateString + ".txt", listZhangHao);
				driver.manage().deleteAllCookies();
				System.out.println("还有(" + listZhangHao.size() + ")个【帐号】没有传输完");
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.getClass().newInstance().do163(filepath, isXiGua);
		}
	};

	// 方法1：
	public static void method1() {
		FileWriter fw = null;
		try {
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File("E:\\dd.txt");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println("追加内容");
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 方法2：
	public static void method2(String file, String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void writeContent(String file, String conent) {
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out.write(conent + "\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 往文件中写内容
	public static void method3(String fileName, String content) throws Exception {
		File file = new File(fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream outputStream = new FileOutputStream(fileName);
		outputStream.write(content.getBytes());
		outputStream.close();
	}

	public static List<String> readFileAll(String filePath) throws IOException {
		File file = new File(filePath);
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		reader = new BufferedReader(new FileReader(file));
		String text = reader.readLine();
		while (text != null) {
			list.add(text.trim() + "\r\n");
			text = reader.readLine();
		}
		reader.close();
		return list;
	}

	public static List<String> readFile(String filePath, String str) throws IOException {
		File file = new File(filePath);
		BufferedReader reader = null;
		List<String> list = new ArrayList<String>();
		reader = new BufferedReader(new FileReader(file));
		String text = reader.readLine();
		while (text != null) {
			if (!text.trim().equals(str)) {
				list.add(text.trim() + "\r\n");
			}
			text = reader.readLine();
		}
		reader.close();
		return list;
	}

	/**
	 * 写文件，不对每一行添加/r/n，之前就有的适合这个
	 */
	public static void writeFile(String filePath, List<String> list) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream outputStream = new FileOutputStream(file);
		for (String s : list) {
			outputStream.write(s.getBytes());
		}
		outputStream.close();
	}

	/**
	 * 写文件，并且对每一行添加/r/n
	 */
	public static void writeFileRN(String filePath, List<String> list) throws IOException {
		File file = new File(filePath);
		if (!file.exists()) {
			file.createNewFile();
		}
		FileOutputStream outputStream = new FileOutputStream(file);
		for (String s : list) {
			outputStream.write((s + "\r\n").getBytes());
		}
		outputStream.close();
	}

	/**
	 * 执行CMD命令,并返回String字符串
	 */
	public static String executeCmd(String strCmd) throws Exception {
		Process p = Runtime.getRuntime().exec("cmd /c " + strCmd);
		StringBuilder sbCmd = new StringBuilder();
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), "GB2312"));
		String line;
		while ((line = br.readLine()) != null) {
			Thread.sleep(300);
			sbCmd.append(line + "\n");
		}
		return sbCmd.toString();
	}

	/**
	 * 连接ADSL
	 * 
	 * @throws Exception
	 */
	public static String connAdsl(String adslZhangHaoReal) throws Exception {
		System.out.println("正在建立连接.");
		String adslName = adslZhangHaoReal.split("-")[0];
		String adslPass = adslZhangHaoReal.split("-")[1];
		String adslTitle = adslZhangHaoReal.split("-")[2];
		String adslCmd = "rasdial " + adslTitle + " " + adslName + " " + adslPass;
		String tempCmd = "";
		tempCmd = executeCmd(adslCmd);
		// 判断是否连接成功
		if (tempCmd.indexOf("已连接") > 0) {
			System.err.println(adslTitle + "IP连接成功....");
			return "已连接";
		} else if (tempCmd.indexOf("已经连接") > 0) {
			System.out.println("IP本来就是连接成功的....");
			return "已连接";
		} else {
			System.err.println(tempCmd);
			for (int i = 0; i < 999; i++) {
				cutAdsl(adslZhangHaoReal);
				Thread.sleep(800);
				String tempCmdFor = executeCmd(adslCmd);
				if (tempCmdFor.indexOf("已连接") > 0) {
					System.err.println("IP连接成功....");
					break;
				} else {
					continue;
				}
			}
			return "已连接";
		}
	}

	/**
	 * 断开ADSL
	 */
	public static String cutAdsl(String adslZhangHaoReal) throws Exception {
		String adslTitle = adslZhangHaoReal.split("-")[2];
		String cutAdsl = "rasdial " + adslTitle + " /disconnect";
		String result = executeCmd(cutAdsl);
		if (result.indexOf("没有连接") != -1) {
			for (int i = 0; i < 999; i++) {
				String cutAdslfor = "rasdial " + adslTitle + " /disconnect";
				String resultfor = executeCmd(cutAdslfor);
				if (resultfor.indexOf("没有连接") != -1) {
					continue;
				} else {
					break;
				}
			}
			System.err.println(adslTitle + "----IP已断开!");
			return "IP已断开!";
		} else {
			System.out.println("IP已断开");
			return "IP已断开!";
		}
	}

	/**
	 * 更换IP 换不成功不要出来
	 */
	public static void changeIP(String adslZhangHaoReal) {
		if (!adslZhangHaoReal.contains("hudq")) {
			ipsRepetition = liantongAdsl;
		}
		for (int j = 0; j < 99999; j++) {
			String ipWai0 = getIPV4();
			if (j == 0) {
				System.out.println("换IP前外网IP为----" + ipWai0);
			}
			int ipslength = ips.size();
			try {
				cutAdsl(adslZhangHaoReal);
				Thread.sleep(800);
				System.out.println("换IP命令执行中----");
				connAdsl(adslZhangHaoReal);
				Thread.sleep(500);
			} catch (Exception e) {
				e.printStackTrace();
			}
			String ipWai1 = getV4IP();
			System.out.println("换IP后外网IP为----" + ipWai1);
			if (ipslength < ipsRepetition && !ips.contains(ipWai1) && ipWai1.length() < 16 && ipWai1.length() > 8) {
				ips.add(0, ipWai1);
				System.err.println("--------IP更换成功,并且不重复");
				System.err.println("❤❤❤❤ IP池子队列的长度为：" + ips.size() + " ❤❤❤❤");
				for (String string : ips) {
					System.err.println("★  ip：" + string.toString() + "  ★");
				}
				System.err.println("❤❤❤❤ IP池子队列的长度为：" + ips.size() + " ❤❤❤❤");
				break;
			} else if (ipslength >= ipsRepetition && !ips.contains(ipWai1) && ipWai1.length() > 8) {
				ips.remove(ipsRepetition - 1);
				ips.add(0, ipWai1);
				System.err.println("--------IP更换成功,并且不重复");
				System.err.println("❤❤❤❤ IP池子队列的长度为：" + ips.size() + " ❤❤❤❤");
				for (String string : ips) {
					System.err.println("★  ip：" + string.toString() + "  ★");
				}
				System.err.println("❤❤❤❤ IP池子队列的长度为：" + ips.size() + " ❤❤❤❤");
				break;
			} else {
				System.out.println("IP重复，重新更换");
			}
		}
	}

	/**
	 * 获取外网IP地址方法1
	 */
	public static String getV4IP() {
		String chinaz = "http://ip.chinaz.com/getip.aspx";
		String inputLine = new String();
		String read = "";
		URL url = null;
		HttpURLConnection urlConnection = null;
		BufferedReader in = null;
		StringBuilder json = new StringBuilder();
		try {
			Thread.sleep(200);
			url = new URL(chinaz);
			urlConnection = (HttpURLConnection) url.openConnection();
			in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
			while ((read = in.readLine()) != null) {
				json.append(read);
			}
			JSONObject userObj = new JSONObject(json.toString());
			inputLine = userObj.optString("ip");
			System.out.println("IP所在地：" + userObj.optString("address"));
			System.out.println(inputLine.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return inputLine;
	}

	/**
	 * 获取外网IP地址方法2
	 */
	public static String getIPV4() {
		String chinaz = "http://httpbin.org/ip";
		String inputLine = new String();
		String read = "";
		URL url = null;
		HttpURLConnection urlConnection = null;
		BufferedReader in = null;
		StringBuilder json = new StringBuilder();
		try {
			Thread.sleep(50);
			url = new URL(chinaz);
			urlConnection = (HttpURLConnection) url.openConnection();
			in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			while ((read = in.readLine()) != null) {
				json.append(read);
			}
			System.err.println(json.toString());
			JSONObject userObj = new JSONObject(json.toString());
			inputLine = userObj.optString("origin");
			System.out.println("getIPV4---IP地址为：" + userObj.optString("origin"));
			// System.out.println(inputLine.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return inputLine;
	}

	/**
	 * 获取类目录
	 */
	public String getClassPath() throws Exception {
		String path = this.getClass().getClassLoader().getResource("").getPath();
		return path;
	}

	/**
	 * 获取项目路径
	 */
	public void showURL() throws IOException {

		// 第一种：获取类加载的根路径 D:\git\daotie\daotie\target\classes
		File f = new File(this.getClass().getResource("/").getPath());
		System.out.println(f);

		// 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录
		// D:\git\daotie\daotie\target\classes\my
		File f2 = new File(this.getClass().getResource("").getPath());
		System.out.println(f2);

		// 第二种：获取项目路径 D:\git\daotie\daotie
		File directory = new File("");// 参数为空
		String courseFile = directory.getCanonicalPath();
		System.out.println(courseFile);

		// 第三种： file:/D:/git/daotie/daotie/target/classes/
		URL xmlpath = this.getClass().getClassLoader().getResource("");
		System.out.println(xmlpath);

		// 第四种： D:\git\daotie\daotie
		System.out.println(System.getProperty("user.dir"));
		/*
		 * 结果： C:\Documents and Settings\Administrator\workspace\projectName
		 * 获取当前工程路径
		 */

		// 第五种： 获取所有的类路径 包括jar包的路径
		System.out.println(System.getProperty("java.class.path"));

	}

	public static void doClean(String filepath) throws Exception {
		// **************生成随机视频文件列表列表****************
		File shiPingAExist = new File(filepath + "/顺序.txt");// 读视频文件
		if (!shiPingAExist.exists()) {

			// **************生成随机视频文件列表列表****************
			String filepath1 = filepath;
			File file = new File(filepath);
			if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					System.gc();
					System.out.println("循环" + (i + 1) + "/" + filelist.length);
					String fileName = filelist[i];
					File fileDel = new File(filepath1 + "/" + fileName);
					if (fileName.endsWith(".txt")) {
						continue;
					}

					if (fileName.length() < 5) {
						System.gc();
						fileDel.delete();
						System.err.println("视频为空标题的直接删除");
						continue;
					}

					String endWith123 = fileName.split(".mp4")[0];
					String str123 = new String(endWith123);
					str123 = endWith123.substring(endWith123.length() - 1, endWith123.length());
					if (isNum(str123)) {
						System.gc();
						fileDel.delete();
						System.err.println("末位为数字的视频删除成功");
						continue;
					}

					if (endingChar(str123)) {
						System.gc();
						fileDel.delete();
						System.err.println("末位为字母的视频删除成功");
						continue;
					}

					if (endWith123.endsWith(")")) {
						System.gc();
						fileDel.delete();
						System.err.println("重复下载的视频删除成功");
						continue;
					}
					if (endWith123.endsWith("）")) {
						System.gc();
						fileDel.delete();
						System.err.println("恶意加符号  ）的视频删除成功");
						continue;
					}
					if (endWith123.length() < 10 || endWith123.length() > 50) {
						System.gc();
						fileDel.delete();
						System.err.println("文件名小于11大于50删除成功");
						continue;
					}
					if (fileName.endsWith(".vd!")) {
						System.gc();
						fileDel.delete();
						System.err.println("维棠未下载完全的删除成功");
						continue;
					}
					if (fileDel.length() > 99999999 || fileDel.length() < 300000) {
						System.gc();
						fileDel.delete();
						System.err.println("文件过大或者过小，删除成功");
						continue;
					}
					if (fileName.endsWith(".ts") || fileName.endsWith(".f4v")) {
						File fileReName = new File(filepath1 + "/" + fileName);
						File mm = new File(filepath1 + "/" + endWith123.split(".f4v")[0].split(".ts")[0] + ".mp4");
						fileReName.renameTo(mm);
						System.err.println("文件改名成功");
						filelist[i] = endWith123.split(".f4v")[0].split(".ts")[0] + ".mp4";
						i--;
						continue;
					}

					try {
						File source = new File(filepath1 + "/" + fileName);
						if (source.exists()) {
							Encoder encoder = new Encoder();
							FileChannel fc = null;
							String size = "";

							it.sauronsoftware.jave.MultimediaInfo m = encoder.getInfo(source);
							long ls = m.getDuration();
							System.out.println("此视频时长为:" + ls / 60000 + "分" + (ls) % 60000 / 1000 + "秒！");
							// 视频帧宽高
							if (m.getVideo() != null) {
								System.out.println("此视频高度为:" + m.getVideo().getSize().getHeight());
								System.out.println("此视频宽度为:" + m.getVideo().getSize().getWidth());
								if (m.getVideo().getSize().getHeight() < 320
										|| m.getVideo().getSize().getWidth() < 320) {
									System.gc();
									fileDel.delete();
									System.err.println("视频帧高度或者宽度低于320，删除成功");
									continue;
								}
							} else {
								System.gc();
								fileDel.delete();
								System.err.println("视频帧高度和宽度读不出来，删除成功");
								continue;
							}
							String videoFormat = m.getFormat();
							System.out.println("此视频格式为:" + videoFormat);
							if (!"mov".equals(videoFormat)) {
								System.gc();
								fileDel.delete();
								System.err.println("非视频格式的要删除，删除成功");
								continue;
							}
							@SuppressWarnings("resource")
							FileInputStream fis = new FileInputStream(source);
							fc = fis.getChannel();
							BigDecimal fileSize = new BigDecimal(fc.size());
							size = fileSize.divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP) + "MB";
							System.out.println("此视频大小为" + size);
						}
					} catch (InputFormatException e) {
						System.gc();
						fileDel.delete();
						System.err.println("视频播放不出来，文件已经损坏，直接删除");
						e.printStackTrace();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (EncoderException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				System.err.println("所有视频处理完毕,下一步准备启动发视频");
			}
		}
	}

	// 1.判断一个字符串的末位字符是否为字母
	public static boolean endingChar(String str) {
		String cString = str.substring(str.length() - 1, str.length());
		char[] cChar = cString.toCharArray();
		int i = (int) cChar[0];
		if ((i >= 65 && i <= 90) || (i >= 97 && i <= 122)) {
			return true;
		} else {
			return false;
		}
	}

	// 2.判断一个字符串的首字符是否为字母
	public static boolean frontChar(String s) {
		char c = s.charAt(0);
		int i = (int) c;
		if ((i >= 65 && i <= 90) || (i >= 97 && i <= 122)) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean check(String fstrData) {
		char c = fstrData.charAt(0);
		if (((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
			return true;
		} else {
			return false;
		}
	}

	// 3 .判断是否为汉字
	public static boolean vd(String str) {

		char[] chars = str.toCharArray();
		boolean isGB2312 = false;
		for (int i = 0; i < chars.length; i++) {
			byte[] bytes = ("" + chars[i]).getBytes();
			if (bytes.length == 2) {
				int[] ints = new int[2];
				ints[0] = bytes[0] & 0xff;
				ints[1] = bytes[1] & 0xff;
				if (ints[0] >= 0x81 && ints[0] <= 0xFE && ints[1] >= 0x40 && ints[1] <= 0xFE) {
					isGB2312 = true;
					break;
				}
			}
		}
		return isGB2312;
	}

	public static boolean isNum(String str) {
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}

	public class TimeoutCallable<V> implements Callable<V> {

		private final Callable<V> callable;
		private final V timeoutV;
		private final long timeout;

		/**
		 * 构造一个 TimeoutCallable
		 *
		 * @param callable
		 *            要运行的 Callable
		 * @param timeout
		 *            Callable 的最大运行时间
		 * @param timeoutV
		 *            Callable 超时的返回结果
		 */
		public TimeoutCallable(Callable<V> callable, long timeout, V timeoutV) {
			this.timeout = timeout;
			this.callable = callable;
			this.timeoutV = timeoutV;
		}

		@Override
		public V call() throws Exception {
			ExecutorService executor = Executors.newSingleThreadExecutor();
			Future<V> future = executor.submit(callable);

			V v = null;
			try {
				v = future.get(timeout, TimeUnit.MILLISECONDS);
			} catch (TimeoutException ex) {
				System.out.println("任务 超时");
			}

			executor.shutdownNow(); // 给线程池中所有正在运行的线程发送 中断 信号

			return v != null ? v : timeoutV;
		}

	}
}
